package com.xdap.fsapproval.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.definesys.mpaas.common.exception.MpaasBusinessException;
import com.xdap.common.util.FeishuStrUtil;
import com.xdap.common.dao.ApprovalDefinitionConfigDao;
import com.xdap.common.dao.ApproveDao;
import com.xdap.common.dao.TenantDatabaseDao;
import com.xdap.common.dao.FeiShuXdapUserDao;
import com.xdap.common.pojo.dto.ApprovalCreateExternalDTO;
import com.xdap.common.pojo.dto.ApprovalCreateViewersDTO;
import com.xdap.common.pojo.dto.ApprovalDto;
import com.xdap.common.pojo.dto.ApprovalInstanceLogsDto;
import com.xdap.common.pojo.dto.webhook.UserDTO;
import com.xdap.common.pojo.dto.webhook.WebhookProcessDto;
import com.xdap.common.pojo.dto.webhook.XdapProcInstanceDto;
import com.xdap.fsapproval.module.dto.syncApprovalInstance.*;
import com.xdap.fsapproval.module.pojo.*;
import com.xdap.fsapproval.pojo.*;
import com.xdap.fsapproval.service.ApprovalService;
import com.xdap.fsapproval.service.FeishuService;
import com.xdap.fsapproval.util.RandomUtil;
import com.xdap.fsapproval.util.TimeUtil;
import com.xdap.fsapproval.util.UrlCodeUtil;
import com.xdap.common.config.LocalValue;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Base64Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;
import java.util.*;

@Service
@Slf4j
@LocalValue
public class ApprovalServiceImpl implements ApprovalService {

    private static Map<String,String> statesMap=new HashMap<>();
    private static List<String> endStatus=new ArrayList<>();
    static {
        //维护已完成状态
        endStatus.add("REJECTED");
        endStatus.add("STOPED");
        endStatus.add("FINISHED");
        endStatus.add("WITHDRAW");
        endStatus.add("SUSPEND");
        endStatus.add("COMPLETED");
        endStatus.add("TERMINATED");

        //维护apaas和飞书的状态关系
        statesMap.put("APPROVING","PENDING");
        statesMap.put("REJECTED","REJECTED");
        statesMap.put("STOPED","REJECTED");
        statesMap.put("TERMINATED","REJECTED");
        statesMap.put("FINISHED","APPROVED");
        statesMap.put("WITHDRAWN","CANCELED");
        statesMap.put("TOREAD","PENDING");
        statesMap.put("HAVEREAD","PENDING");
        statesMap.put("SUSPEND","PENDING");
        statesMap.put("COMPLETED","APPROVED");
        statesMap.put("REFUSED","REJECTED");

    }

    private static final String ContentType ="application/json; charset=utf-8";

    @LocalValue("${feishu.application.defineApprovalUrl}")
    private String DefineApprovalUrl;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private FeishuService feishuService;

    @LocalValue("${feishu.sync.approvalInstance.url}")
    private String approvalInstanceUrl;

    @LocalValue("${feishu.sync.approva.toApaasUrl}")
    private String toApaasUrl;

    @LocalValue("${feishu.application.client_id}")
    private String clientId;

    @LocalValue("${feishu.apaas.url}")
    private String apaasUrl;

    @LocalValue("${feishu.sendApprovalBotUrl}")
    private String sendApprovalBotUrl;

    @Autowired
    TenantDatabaseDao tenantDatabaseDao;


    @Autowired
    ApprovalDefinitionConfigDao approvalDefinitionConfigDao;

    @Autowired
    FeiShuXdapUserDao feiShuXdapUserDao;

    @Autowired
    ApproveDao approveDao;


    @Override
    public ApprovalInstanceLogsDto defineApproval(XdapProcInstanceDto xdapProcInstanceDto) {
        ApprovalInstanceLogsDto approvalInstanceLogsDto = new ApprovalInstanceLogsDto();
        if (xdapProcInstanceDto!=null) {
            //设置请求体
            ApprovalDto approvalDto = new ApprovalDto();
            approvalDto.setApprovalCode(xdapProcInstanceDto.getFormId());
            approvalDto.setGroupCode("apaas_group");
            approvalDto.setGroupName("apaas审批");
            //三方审批相关 state参数组成
            //消息跳转需要的参数
            M1 m1 = new M1();
            m1.setAppId(xdapProcInstanceDto.getAppId());
            m1.setFormId(xdapProcInstanceDto.getFormId());
            m1.setModule("insertPage");
            String menuId = xdapProcInstanceDto.getMenuId();
            XdapMenus xdapMenus = approveDao.selectTitle(menuId,xdapProcInstanceDto.getTenantId());
            approvalInstanceLogsDto.setMenuName(xdapMenus.getMenuName());
            if (xdapMenus!=null){
                approvalDto.setApprovalName(xdapMenus.getMenuName());
                String title = xdapMenus.getMenuName();
                String encodeTitle = UrlCodeUtil.encodeString(title);
                m1.setTitle(encodeTitle);
            }
            InsertState insertState = new InsertState();
            insertState.setM1(m1);
            //跳转平台，固定为workbench; 跳转应用，固定为应用的id;
            insertState.setA1(xdapProcInstanceDto.getAppId());
            //租户id
            insertState.setT1(xdapProcInstanceDto.getTenantId());
            //数据库中企业微信单条配置数据的id(xdap_work_wechat_configs表的主键)
            XdpFeiShuConfigs xdpFeiShuConfigs = approveDao.selectId(xdapProcInstanceDto.getAppId(), xdapProcInstanceDto.getTenantId());
            if (xdpFeiShuConfigs!=null){
                String w1 = xdpFeiShuConfigs.getId();
                insertState.setW1(w1);
            }
            //pc端链接
            insertState.setClient("pc");
            String pcState = Base64Util.encode(JSON.toJSONString(insertState));
            //移动端链接
            insertState.setClient("mobile");
            String mobleState = Base64Util.encode(JSON.toJSONString(insertState));
            ApprovalCreateExternalDTO external = new ApprovalCreateExternalDTO();
            ApaasApplications apaasApplications = approveDao.selectUrl(xdapProcInstanceDto.getAppId(), xdapProcInstanceDto.getTenantId());
            if (apaasApplications!=null){
                String dburl = apaasApplications.getAccessUrl()+"callback/feishu/index.html&app_id="+xdpFeiShuConfigs.getFeishuAppId()+"&state=";
                String toApaas = UrlCodeUtil.encodeString(apaasUrl);
                String pcLkTargetUrl = toApaas+UrlCodeUtil.encodeString(dburl)+pcState;
                String mobileLkTargetUrl = toApaas+UrlCodeUtil.encodeString(dburl)+mobleState;
                String pcUrl = toApaasUrl.replaceAll("#appId", xdpFeiShuConfigs.getFeishuAppId()).replaceAll("#url", pcLkTargetUrl);
                String mobleUrl = toApaasUrl.replaceAll("#appId", xdpFeiShuConfigs.getFeishuAppId()).replaceAll("#url", mobileLkTargetUrl);
                external.setCreateLinkPc(pcUrl);
                external.setCreateLinkMobile(mobleUrl);
                approvalInstanceLogsDto.setPcLink(pcUrl);
                approvalInstanceLogsDto.setMobileLink(mobleUrl);
            }
            external.setSupportPc(true);
            external.setSupportMobile(true);
            external.setSupportBatchRead(false);
            external.setBizName("aPaaS待办");
            external.setExcludeEfficiencyStatistics(true);
            approvalDto.setExternal(external);

            //可见人列表
            ApprovalCreateViewersDTO viewers = new ApprovalCreateViewersDTO();
            List<ApprovalCreateViewersDTO> viewersDTOList = new ArrayList<>();
            viewers.setViewerType("TENANT");
            viewersDTOList.add(viewers);
            approvalDto.setViewers(viewersDTOList);

            //根据user_id_type类型  填写流程管理员id
//            List<String> managers = new ArrayList<>();
//            managers.add("4c675438");
//            approvalDto.setManagers(managers);

            log.info("创建飞书审批定义----->" + JSONObject.toJSONString(approvalDto));
            //创建飞书审批流程定义
            approvalInstanceLogsDto.setCode(sendFeishuApprovel(approvalDto));
            return approvalInstanceLogsDto;
        }else {
            return null;
        }

    }


    /**
     * 创建飞书审批流程定义
     * @param approvalDto
     * @return
     */
    public String sendFeishuApprovel(ApprovalDto approvalDto){
        //获取飞书token
        String feishuToken = feishuService.getToken();
        //设置请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Authorization", "Bearer " + feishuToken);
        httpHeaders.set("Content-Type", ContentType);
        // 封装参数和头信息
        String jsonString = JSONObject.toJSONString(approvalDto, SerializerFeature.WriteMapNullValue);
        HttpEntity<JSONObject> httpEntity = new HttpEntity(jsonString, httpHeaders);
        ResponseEntity<String> mapResponseEntity = restTemplate.postForEntity(DefineApprovalUrl, httpEntity, String.class);
        HashMap hashMap = JSON.parseObject(mapResponseEntity.getBody(), HashMap.class);
        Map approvalCode = (Map) hashMap.get("data");
        log.info(mapResponseEntity.getBody());
        return (String) approvalCode.get("approval_code");

    }

    @Override
    public void  consolidationApprovalData(WebhookProcessDto webhookProcessDto){
        ApprovalInstanceLogs approvalInstanceLogs=new ApprovalInstanceLogs();
        //构建发送飞书审批实例id
        ApprovalInstanceDto approvalInstanceDto = new ApprovalInstanceDto();
        //webhook接收到apaas流程信息
        XdapProcInstanceDto xdapProcInstance = webhookProcessDto.getXdapProcInstance();
        LinksDTO linksDTO=new LinksDTO();
        try {
            log.info("接受webHook请求数据----->" + JSONObject.toJSONString(webhookProcessDto));
            //发送飞书审批消息
            sendApprovalBot(webhookProcessDto);
            //定义当前审批访问地址
            linksDTO = buildLikeUrl(webhookProcessDto, false);
            //1、根据formId获取飞书审批定义编码
            ApprovalDefinitionConfig approvalDefinitionConfig = approvalDefinitionConfigDao.getFeishu(xdapProcInstance.getFormId());
            approvalInstanceDto.setApprovalCode(approvalDefinitionConfig.getFeishuApprovalCode());
            approvalInstanceDto.setInstanceId(xdapProcInstance.getDocumentId());
            approvalInstanceDto.setLinks(linksDTO);
            approvalInstanceDto.setUpdateMode("REPLACE");
            approvalInstanceDto.setDisplayMethod("NORMAL");
            //维护审批定义列表展示的字段
            List<FormDTO> formDTOList = new ArrayList<>();
            formDTOList.add(FormDTO.builder(xdapProcInstance.getFirstLabel(), xdapProcInstance.getFirstData()));
            formDTOList.add(FormDTO.builder(xdapProcInstance.getSecondLabel(), xdapProcInstance.getSecondData()));
            formDTOList.add(FormDTO.builder(xdapProcInstance.getThirdLabel(), xdapProcInstance.getThirdData()));
            approvalInstanceDto.setForm(formDTOList);
            //设置审批状态
            approvalInstanceDto.setStatus(statesMap.get(xdapProcInstance.getStatus()));
            //审批开始时间
            approvalInstanceDto.setStartTime(TimeUtil.ConversionTimestamp(xdapProcInstance.getSubmitTime()));
            //审批修改日期时间
            approvalInstanceDto.setUpdateTime(String.valueOf(System.currentTimeMillis()));
            //审批结束时间
            //如果是已拒绝、已终止、已完成、已撤回、挂起中结束时间为当前时间
            if (endStatus.contains(xdapProcInstance.getStatus())) {
                approvalInstanceDto.setEndTime(approvalInstanceDto.getUpdateTime());
            } else {
                //否则结束时间为0
                approvalInstanceDto.setEndTime("0");
            }
            //2、构建流程发起人数据
            //流程发起人信息
            XdapUsers submitter = feiShuXdapUserDao.getXdapUserInfo(xdapProcInstance.getSubmitter(), webhookProcessDto.getTenantId(), "xdap_users");
            approvalInstanceDto.setUserId(submitter.getRefId());
            approvalInstanceDto.setUserName(submitter.getUsername());
            //3、构建任务集合
            List<TaskListDTO> taskListDTOS = new ArrayList<>();
            //3.1构建待办->审批人
            List<UserDTO> approverDTO = xdapProcInstance.getApproverDTO();
            if (!CollectionUtils.isEmpty(approverDTO)) {
                if (!"TOREAD".equals(xdapProcInstance.getStatus()) && !"HAVEREAD".equals(xdapProcInstance.getStatus()) || !"NORMAL_TERMINATE".equals(xdapProcInstance.getStatus())) {
                    List<String> userIds = new ArrayList<>();
                    for (UserDTO userDTO : approverDTO) {
                        userIds.add(userDTO.getUserId());
                    }
                    List<XdapUsers> xdapUsers = feiShuXdapUserDao.getXdapUserInfo(userIds, webhookProcessDto.getTenantId(), "xdap_users");
                    for (XdapUsers xdapUser : xdapUsers) {
                        TaskListDTO taskListDTO = new TaskListDTO();
                        taskListDTO.setDisplayMethod("NORMAL");
                        taskListDTO.setUserId(xdapUser.getRefId());
                        taskListDTO.setCreateTime(String.valueOf(System.currentTimeMillis()));
                        taskListDTO.setEndTime("0");
                        taskListDTO.setStatus("PENDING");
                        taskListDTO.setTaskId(RandomUtil.getRandom(6));
                        LinksDTO taskLinksDTO = new LinksDTO();
                        taskLinksDTO.setMobileLink(linksDTO.getMobileLink());
                        taskLinksDTO.setPcLink(linksDTO.getPcLink());
                        taskListDTO.setLinks(taskLinksDTO);
                        taskListDTOS.add(taskListDTO);
                    }
                }
            }
            //3.2构建已办
            //3.2.1查询已办列表
            if (StringUtils.isNotBlank(xdapProcInstance.getInstanceId())) {
                List<String> taskIdList = new ArrayList<>();
                List<XdapApproveHistory> xdapApproveHistorys = approveDao.listXdapApproveHistory(xdapProcInstance.getInstanceId(), webhookProcessDto.getTenantId(), "xdap_approve_history");
                for (int i = 0; i < xdapApproveHistorys.size(); i++) {

                    if("NORMAL_TERMINATE".equals(xdapApproveHistorys.get(i).getOperateType())){
                        xdapApproveHistorys.get(i).setTaskId(RandomUtil.getRandom(6));
                    }
                    if ("SUBMIT".equals(xdapApproveHistorys.get(i).getOperateType())
                            || "RESTART".equals(xdapApproveHistorys.get(i).getOperateType())
                            || "REASSIGN".equals(xdapApproveHistorys.get(i).getOperateType())
                            || "NODE_END".equals(xdapApproveHistorys.get(i).getOperateType())
                            || "INQUIRE".equals(xdapApproveHistorys.get(i).getOperateType())
                            || "FRONTADDONE".equals(xdapApproveHistorys.get(i).getOperateType())
                            || StringUtils.isBlank(xdapApproveHistorys.get(i).getTaskId())) {
                        continue;
                    } else {
                        XdapUsers approveUser = feiShuXdapUserDao.getXdapUserInfo(xdapApproveHistorys.get(i).getApproveId(), webhookProcessDto.getTenantId(), "xdap_users");
                        TaskListDTO taskListDTO = new TaskListDTO();
                        taskListDTO.setDisplayMethod("NORMAL");
                        taskListDTO.setUserId(approveUser.getRefId());
                        taskListDTO.setCreateTime(String.valueOf(xdapApproveHistorys.get(i - 1).getApproveDate().getTime()));
                        taskListDTO.setEndTime(String.valueOf(xdapApproveHistorys.get(i).getApproveDate().getTime()));
                        taskListDTO.setStatus("REJECT".equals(xdapApproveHistorys.get(i).getOperateType()) ? "REJECTED" : "APPROVED");
                        if (taskIdList.contains(xdapApproveHistorys.get(i).getTaskId())) {
                            taskListDTO.setTaskId(xdapApproveHistorys.get(i).getId());
                        } else {
                            taskListDTO.setTaskId(xdapApproveHistorys.get(i).getTaskId());
                            taskIdList.add(xdapApproveHistorys.get(i).getTaskId());
                        }
                        LinksDTO taskLinksDTO = new LinksDTO();
                        taskLinksDTO.setMobileLink(linksDTO.getMobileLink());
                        taskLinksDTO.setPcLink(linksDTO.getPcLink());
                        taskListDTO.setLinks(taskLinksDTO);
                        taskListDTOS.add(taskListDTO);
                    }
                }
            }
            //构建抄送列表
            List<ApaasProcNotificationLog> apaasProcNotificationLogs = approveDao.selectApaasProcNotificationLog(xdapProcInstance.getDocumentId(), webhookProcessDto.getTenantId());
            if (!CollectionUtils.isEmpty(apaasProcNotificationLogs)) {
                List<CcNode> ccNodes = new ArrayList<>();
                for (ApaasProcNotificationLog apaasProcNotificationLog : apaasProcNotificationLogs) {
                    CcNode ccNode = new CcNode();
                    ccNode.setCcId(apaasProcNotificationLog.getId());
                    XdapUsers approveUser = feiShuXdapUserDao.getXdapUserInfo(apaasProcNotificationLog.getReceiver(), webhookProcessDto.getTenantId(), "xdap_users");
                    ccNode.setUserId(approveUser.getRefId());
                    ccNode.setReadStatus("WAIT_CHECK".equals(apaasProcNotificationLog.getCheckStatus()) ? "UNREAD" : "READ");
                    ccNode.setDisplayMethod("NORMAL");
                    ccNode.setCreateTime(String.valueOf(apaasProcNotificationLog.getCreationDate().getTime()));
                    ccNode.setUpdateTime(String.valueOf(apaasProcNotificationLog.getLastUpdateDate().getTime()));
                    LinksDTO linksDTOCc = new LinksDTO();
                    linksDTOCc.setPcLink(linksDTO.getPcLink());
                    linksDTOCc.setMobileLink(linksDTO.getMobileLink());
                    ccNode.setLinks(linksDTOCc);
                    ccNodes.add(ccNode);
                }
                approvalInstanceDto.setCcList(ccNodes);
            }
            approvalInstanceDto.setTaskList(taskListDTOS);
            //4、构建国际化语言
            List<I18nResourcesDTO> i18nResourcesDTOList = new ArrayList<>();
            List<TextsDTO> textsDTOS = new ArrayList<>();
            textsDTOS.add(TextsDTO.builder("@i18n@1", "demo"));
            i18nResourcesDTOList.add(I18nResourcesDTO.builder(textsDTOS));
            approvalInstanceDto.setI18nResources(i18nResourcesDTOList);
            //5、推送飞书审批
            log.info("推送飞书审批实例----->" + JSONObject.toJSONString(approvalInstanceDto));
            syncApprovalInstance(approvalInstanceDto);
            //记录推送日志
        }catch (Exception e){
            e.printStackTrace();
            approvalInstanceLogs.setErrorLog(e.getMessage());
        } finally {
            approvalInstanceLogs.setOwner(xdapProcInstance.getSubmitter());
            approvalInstanceLogs.setCreatedBy(xdapProcInstance.getSubmitter());
            approvalInstanceLogs.setLastUpdatedBy(xdapProcInstance.getSubmitter());
            approvalInstanceLogs.setFormId(xdapProcInstance.getFormId());
            approvalInstanceLogs.setDocumentId(xdapProcInstance.getDocumentId());
            approvalInstanceLogs.setPcLink(linksDTO.getPcLink());
            approvalInstanceLogs.setMobileLink(linksDTO.getMobileLink());
            approvalInstanceLogs.setFeishuApprovalText(JSONObject.toJSONString(approvalInstanceDto));
            approvalInstanceLogs.setWebhookText(JSONObject.toJSONString(webhookProcessDto));
            createApprovalInstanceLogs(approvalInstanceLogs);
        }
    }

    public LinksDTO buildLikeUrl(WebhookProcessDto webhookProcessDto,boolean hasAppLink){
        LinksDTO linksDTO = new LinksDTO();
        try {
            InsertState insertState = new InsertState();
            insertState.setA1(webhookProcessDto.getAppId());
            XdpFeiShuConfigs xdpFeiShuConfigs = approveDao.selectId(webhookProcessDto.getAppId(), webhookProcessDto.getTenantId());
            if (xdpFeiShuConfigs != null) {
                String w1 = xdpFeiShuConfigs.getId();
                insertState.setW1(w1);
            }
            insertState.setT1(webhookProcessDto.getTenantId());
            M1 m1 = new M1();
            m1.setFormId(webhookProcessDto.getXdapProcInstance().getFormId());
            m1.setCurrentMenu(webhookProcessDto.getXdapProcInstance().getMenuId());
            m1.setDocumentId(webhookProcessDto.getXdapProcInstance().getDocumentId());
            m1.setAppId(webhookProcessDto.getAppId());
            m1.setModule("approvePage");
            m1.setReadOnly("isApprove");
            XdapMenus xdapMenus = approveDao.selectTitle(webhookProcessDto.getXdapProcInstance().getMenuId(), webhookProcessDto.getTenantId());
            if (xdapMenus != null) {
                String title = xdapMenus.getMenuName();
                m1.setTitle(title);
            }
            XdapTenantDatabase xdapTenantDatabase = tenantDatabaseDao.getXdapTenantDatabase(webhookProcessDto.getTenantId());
            if (!Objects.isNull(xdapTenantDatabase)) {
                String tabId = tenantDatabaseDao.getTabId(webhookProcessDto.getXdapProcInstance().getFormId(),webhookProcessDto.getTenantId());
                m1.setTabId(tabId);
            }
            insertState.setM1(m1);
            //pc端链接
            insertState.setClient("pc");
            String pcUrlInsertState = URLEncoder.encode(JSONObject.toJSONString(insertState), "utf-8");
            //移动端链接
            insertState.setClient("mobile");
            String mobileUrlInsertState = URLEncoder.encode(JSONObject.toJSONString(insertState), "utf-8");
            String pcState=new String(Base64.getEncoder().encode(pcUrlInsertState.getBytes()));
            String mobileState=new String(Base64.getEncoder().encode(mobileUrlInsertState.getBytes()));
            ApaasApplications apaasApplications = approveDao.selectUrl(webhookProcessDto.getAppId(), webhookProcessDto.getTenantId());
            if (apaasApplications!=null){
                String uri = apaasApplications.getAccessUrl()+"callback/feishu/index.html";
                if (hasAppLink){
                    String pcLkTargetUrl = UrlCodeUtil.encodeString(apaasUrl+UrlCodeUtil.encodeString(uri)+"&app_id="+xdpFeiShuConfigs.getFeishuAppId()+"&state="+pcState);
                    String mobileLkTargetUrl = UrlCodeUtil.encodeString(apaasUrl+UrlCodeUtil.encodeString(uri)+"&app_id="+xdpFeiShuConfigs.getFeishuAppId()+"&state="+mobileState);
                    linksDTO.setMobileLink(toApaasUrl.replace("#appId", approveDao.selectId(webhookProcessDto.getXdapProcInstance().getAppId(), webhookProcessDto.getXdapProcInstance().getTenantId()).getFeishuAppId()).replace("#url",mobileLkTargetUrl));
                    linksDTO.setPcLink(toApaasUrl.replace("#appId", approveDao.selectId(webhookProcessDto.getXdapProcInstance().getAppId(), webhookProcessDto.getXdapProcInstance().getTenantId()).getFeishuAppId()).replace("#url",pcLkTargetUrl));
                }else {
                    String pcLkTargetUrl = apaasUrl+UrlCodeUtil.encodeString(uri)+"&app_id="+xdpFeiShuConfigs.getFeishuAppId()+"&state="+pcState;
                    String mobileLkTargetUrl = apaasUrl+UrlCodeUtil.encodeString(uri)+"&app_id="+xdpFeiShuConfigs.getFeishuAppId()+"&state="+mobileState;
                    linksDTO.setPcLink(pcLkTargetUrl);
                    linksDTO.setMobileLink(mobileLkTargetUrl);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new MpaasBusinessException("构建表单详情url失败");
        }
        return linksDTO;
    }

    public void createApprovalInstanceLogs(ApprovalInstanceLogs approvalInstanceLogs){
        Integer integer = approvalDefinitionConfigDao.updateApprovalInstanceLogs(approvalInstanceLogs);
        if(integer<1){
            approvalDefinitionConfigDao.insertApprovalInstanceLogs(approvalInstanceLogs);
        }
    }

    /**
     * 同步飞书审批实例
     * @param approvalInstanceDto
     */
    public void syncApprovalInstance(ApprovalInstanceDto approvalInstanceDto){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Authorization","Bearer "+feishuService.getToken());
        httpHeaders.set("Content-Type", ContentType);
        HttpEntity<JSONObject> httpEntity = new HttpEntity(JSONObject.toJSONString(approvalInstanceDto), httpHeaders);
        ResponseEntity<String> mapResponseEntity = restTemplate.postForEntity(approvalInstanceUrl, httpEntity, String.class);
        log.info("同步飞书审批实例返回结果："+mapResponseEntity.getBody());

    }



    @Override
    public void sendApprovalBot(WebhookProcessDto webhookProcessDto){
        log.info("进入发送审批消息方法："+JSONObject.toJSONString(webhookProcessDto));
        if (FeishuStrUtil.isNotEmpty(webhookProcessDto.getApaasProcNotificationLog())){
            log.info("发送知会信息："+JSONObject.toJSONString(webhookProcessDto.getApaasProcNotificationLog()));
            if (("WAIT_CHECK").equals(webhookProcessDto.getApaasProcNotificationLog().getCheckStatus())){
                log.info("准备发送知会信息");
                 sendBotToReceiver(webhookProcessDto);
                 return;
            }
        }
        try {
            if (FeishuStrUtil.isNotEmpty(webhookProcessDto.getXdapProcInstance())){
                String buttonCode="SUBMIT";
                if(StringUtils.isNotBlank(webhookProcessDto.getXdapProcInstance().getButtonCode())){
                    buttonCode=webhookProcessDto.getXdapProcInstance().getButtonCode();
                }else if (FeishuStrUtil.isNotEmpty(webhookProcessDto.getBusinessData())&&StringUtils.isNotBlank(webhookProcessDto.getBusinessData().getButtonCode())){
                    log.info("buttonCode没有接受到值："+JSONObject.toJSONString(webhookProcessDto));
                    buttonCode=webhookProcessDto.getBusinessData().getButtonCode();
                }
                switch (buttonCode){
                    //提交 给审批人发送消息：   ——XXX提交的xxx流程待你审批
                    case "SUBMIT":
                        sendApprovalBotToNextApproval(webhookProcessDto.getXdapProcInstance(),"待你审批");
                         break;
                    //同意 给发起人：——你发起的xxx流程，已通过xxx审批， 给下一审批人发送消息：——XXX提交的xxx流程待你审批
                    case "APPROVE":
                         sendApprovalBotToCreatedBy(webhookProcessDto.getXdapProcInstance(),"审批通过");
                         sendApprovalBotToNextApproval(webhookProcessDto.getXdapProcInstance(),"待你审批");
                         break;

                    //拒绝 给发起人发送消息：——你发起的xxx流程，已被xxx拒绝
                    case "REJECT":
                        sendApprovalBotToCreatedBy(webhookProcessDto.getXdapProcInstance(),"拒绝");
                        break;
                    //撤回  无需操作
                    //征询  给征询人送消息：XXX提交的XXX需要你回复
                    case "INQUIRE":
                        sendApprovalBotToNextApproval(webhookProcessDto.getXdapProcInstance(),"需要你回复");
                        break;
                    //回复 ,"回复" 给下一审批人送消息： ——xxx提交的流程待你审批
                    case "REPLY":
                    //流程转交 给转交人发送消息： ——xxx提交的流程待你审批
                    case "REASSIGN":
                    //前加签 给加签人发送消息: ——xxx提交的流程待你审批
                    case "FRONTADDONE":
                    //重新提交  给审批人发送消息：—xxx提交的流程待你审批
                    case "RESTART":
                    //加签 "加签" 给加签人发送消息: ——xxx提交的流程待你审批
                    case "ADDONE":
                    //流程代办转交 给转交人发送消息： ——xxx提交的流程待你审批
                    case "PROCESS_TODO_REASSIGN":
                        sendApprovalBotToNextApproval(webhookProcessDto.getXdapProcInstance(),"待你审批");
                        break;
                    //终止 给发起人发消息， ——你发起的xxx流程，已被xxx终止
                    case "TERMINATE":
                        sendApprovalBotToCreatedBy(webhookProcessDto.getXdapProcInstance(),"终止");
                        break;
                    //挂起 给发起人发消息  ——你发起的xxx流程，已被xxx挂起
                    case "SUSPEND":
                        sendApprovalBotToCreatedBy(webhookProcessDto.getXdapProcInstance(),"挂起");
                        break;
                    //激活 给发起人发消息， ——你发起的xxx流程，已被xxx激活
                    case "ACTIVITY":
                        sendApprovalBotToCreatedBy(webhookProcessDto.getXdapProcInstance(),"激活");
                        break;
                }
             }
    }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 给下一个审批人发送bot消息
     * @param xdapProcInstanceDto
     *
     */
    public void sendApprovalBotToNextApproval(XdapProcInstanceDto xdapProcInstanceDto,String result) {
        //拿到下一审批人信息
        List<UserDTO> approverDTO = xdapProcInstanceDto.getApproverDTO();
        //流程名称
        String titleName =  approveDao.selectTitle(xdapProcInstanceDto.getMenuId(), xdapProcInstanceDto.getTenantId()).getMenuName();
        //流程创建人名称
        String creatName =  feiShuXdapUserDao.getXdapUserInfo(xdapProcInstanceDto.getSubmitter(), xdapProcInstanceDto.getTenantId(), "xdap_users").getUsername();
        WebhookProcessDto webhookProcessDto = new WebhookProcessDto();
        webhookProcessDto.setAppId(xdapProcInstanceDto.getAppId());
        webhookProcessDto.setTenantId(xdapProcInstanceDto.getTenantId());
        webhookProcessDto.setXdapProcInstance(xdapProcInstanceDto);
        LinksDTO linksDTO = buildLikeUrl(webhookProcessDto,true);
        log.info("推送审批消息体链接："+JSONObject.toJSONString(linksDTO));
        if (!CollectionUtils.isEmpty(approverDTO)) {
            for (UserDTO userDTO : approverDTO) {
                //创建一个Bot对象
                ApprovalBotSend approvalBotSend = new ApprovalBotSend();
                //卡片模板
                approvalBotSend.setTemplateId("1021");
                //需要推送的用户信息
                XdapUsers xdapUsers = feiShuXdapUserDao.getXdapUserInfo(userDTO.getUserId(), xdapProcInstanceDto.getTenantId(), "xdap_users");
                log.info("审批人的信息："+xdapUsers);
                approvalBotSend.setUserId(xdapUsers.getRefId());
                //唯一标识
                approvalBotSend.setUuid(UUID.randomUUID().toString());
                //bot标题
                approvalBotSend.setCustomTitle("@i18n@1");
                //bot内容
                approvalBotSend.setCustomContent("@i18n@2");
                //行动区
                List<ApprovalBotActions> approvalBotActionsList = new ArrayList<>();
                ApprovalBotActions approvalBotActions = new ApprovalBotActions();
                //bot底下按钮 固定为：查看详情
                approvalBotActions.setActionName("@i18n@4");
                //获取url
                approvalBotActions.setAndroidUrl(linksDTO.getMobileLink());
                approvalBotActions.setUrl(linksDTO.getPcLink());
                approvalBotActions.setIosUrl(linksDTO.getMobileLink());
                approvalBotActions.setPcUrl(linksDTO.getPcLink());
                approvalBotActionsList.add(approvalBotActions);
                approvalBotSend.setActions(approvalBotActionsList);
                //国际化文案
                List<ApprovalBotI18nResources> i18nResourcesList = new ArrayList<>();
                ApprovalBotI18nResources i18nResources = new ApprovalBotI18nResources();
                //是否为默认语音
                i18nResources.setIsDefault(true);
                //设置为中文
                i18nResources.setLocale("zh-CN");
                ApprovalBotI18nResourcesTexts texts = new ApprovalBotI18nResourcesTexts();
                //按钮名称
                texts.setActionName1("查看详情");
                //卡片内容
                String customContent = "**流程详情:**\n";
                        if (StringUtils.isNotBlank(xdapProcInstanceDto.getFirstLabel())&&StringUtils.isNotBlank(xdapProcInstanceDto.getFirstData())){
                            customContent = customContent + xdapProcInstanceDto.getFirstLabel() + ":" + xdapProcInstanceDto.getFirstData().replace("\"","")+ "\n";
                        }
                        if (StringUtils.isNotBlank(xdapProcInstanceDto.getSecondLabel())&&StringUtils.isNotBlank(xdapProcInstanceDto.getSecondData())){
                            customContent = customContent    + xdapProcInstanceDto.getSecondLabel() + ":" + xdapProcInstanceDto.getSecondData().replace("\"","") + "\n" ;
                        }
                        if (StringUtils.isNotBlank(xdapProcInstanceDto.getThirdLabel())&&StringUtils.isNotBlank(xdapProcInstanceDto.getThirdData())){
                            customContent = customContent + xdapProcInstanceDto.getThirdLabel() + ":" + xdapProcInstanceDto.getThirdData().replace("\"","");
                        }

                texts.setCustomContent(customContent);
                //发送卡片标题
                texts.setCustomTitle(creatName+"提交的"+titleName+"流程"+result);
                i18nResources.setTexts(texts);
                i18nResourcesList.add(i18nResources);
                approvalBotSend.setI18nResources(i18nResourcesList);
                log.info("发送审批消息体："+JSONObject.toJSONString(approvalBotSend));
                ResponseEntity mapResponseEntity = sendBot(approvalBotSend);
                log.info("发送审批Bot消息结果：" + mapResponseEntity.getBody());
            }
            log.info("发送审批bot成功！");
        } else {
            log.info("没有下一个审批人");
        }

    }

    /**
     * 给发起人发送bot消息
     * @param xdapProcInstanceDto
     */
    public void sendApprovalBotToCreatedBy(XdapProcInstanceDto xdapProcInstanceDto,String result) {
        //创建一个Bot对象
        ApprovalBotSend approvalBotSend = new ApprovalBotSend();
        //卡片模板
        approvalBotSend.setTemplateId("1021");
        //推送给审批用户的信息
        XdapUsers xdapUsers = feiShuXdapUserDao.getXdapUserInfo(xdapProcInstanceDto.getSubmitter(), xdapProcInstanceDto.getTenantId(), "xdap_users");
        approvalBotSend.setUserId(xdapUsers.getRefId());
        //唯一值
        approvalBotSend.setUuid(UUID.randomUUID().toString());
        //bot标题
        approvalBotSend.setCustomTitle("@i18n@1");
        //bot内容
        approvalBotSend.setCustomContent("@i18n@2");
        //行动区
        List<ApprovalBotActions> approvalBotActionsList = new ArrayList<>();
        ApprovalBotActions approvalBotActions = new ApprovalBotActions();
        approvalBotActions.setActionName("@i18n@4");
        WebhookProcessDto webhookProcessDto = new WebhookProcessDto();
        webhookProcessDto.setAppId(xdapProcInstanceDto.getAppId());
        webhookProcessDto.setTenantId(xdapProcInstanceDto.getTenantId());
        webhookProcessDto.setXdapProcInstance(xdapProcInstanceDto);
        LinksDTO linksDTO = buildLikeUrl(webhookProcessDto,true);
        log.info("发送审批消息跳转链接："+JSONObject.toJSONString(linksDTO));
        approvalBotActions.setAndroidUrl(linksDTO.getMobileLink());
        approvalBotActions.setUrl(linksDTO.getPcLink());
        approvalBotActions.setIosUrl(linksDTO.getMobileLink());
        approvalBotActions.setPcUrl(linksDTO.getPcLink());
        approvalBotActionsList.add(approvalBotActions);
        approvalBotSend.setActions(approvalBotActionsList);
        //国际化文案
        List<ApprovalBotI18nResources> i18nResourcesList = new ArrayList<>();
        ApprovalBotI18nResources i18nResources = new ApprovalBotI18nResources();
        i18nResources.setIsDefault(true);
        i18nResources.setLocale("zh-CN");
        ApprovalBotI18nResourcesTexts texts = new ApprovalBotI18nResourcesTexts();
        texts.setActionName1("查看详情");
        //卡片内容
        String customContent = "**流程详情:**\n";
        if (StringUtils.isNotBlank(xdapProcInstanceDto.getFirstLabel())&&StringUtils.isNotBlank(xdapProcInstanceDto.getFirstData())){
            customContent = customContent + xdapProcInstanceDto.getFirstLabel() + ":" + xdapProcInstanceDto.getFirstData().replace("\"","")+ "\n";
        }
        if (StringUtils.isNotBlank(xdapProcInstanceDto.getSecondLabel())&&StringUtils.isNotBlank(xdapProcInstanceDto.getSecondData())){
            customContent = customContent    + xdapProcInstanceDto.getSecondLabel() + ":" + xdapProcInstanceDto.getSecondData().replace("\"","") + "\n" ;
        }
        if (StringUtils.isNotBlank(xdapProcInstanceDto.getThirdLabel())&&StringUtils.isNotBlank(xdapProcInstanceDto.getThirdData())){
            customContent = customContent + xdapProcInstanceDto.getThirdLabel() + ":" + xdapProcInstanceDto.getThirdData().replace("\"","");
        }
        texts.setCustomContent(customContent);
        //上一个操作人信息
        XdapUsers approveUser = feiShuXdapUserDao.getXdapUserInfo(xdapProcInstanceDto.getLastUpdatedBy(), xdapProcInstanceDto.getTenantId(), "xdap_users");
        //流程名称
        String titleName =  approveDao.selectTitle(xdapProcInstanceDto.getMenuId(), xdapProcInstanceDto.getTenantId()).getMenuName();
        //bot标题
        String title = "你发起的"+titleName+"流程，已被"+approveUser.getUsername()+result;
        texts.setCustomTitle(title);
        i18nResources.setTexts(texts);
        i18nResourcesList.add(i18nResources);
        approvalBotSend.setI18nResources(i18nResourcesList);
        log.info("发送审批消息："+JSONObject.toJSONString(approvalBotSend));
        ResponseEntity mapResponseEntity = sendBot(approvalBotSend);
        log.info("发送审批Bot消息结果：" + mapResponseEntity.getBody());

    }

    /**
     * 给知会接收人发bot信息
     */
    public String sendBotToReceiver(WebhookProcessDto webhookProcessDto){
        log.info("发送知会消息接受的数据："+JSONObject.toJSONString(webhookProcessDto));
        //创建一个Bot对象
        ApprovalBotSend approvalBotSend = new ApprovalBotSend();
        //卡片模板
        approvalBotSend.setTemplateId("1021");
        //推送给审批用户的信息
        XdapUsers xdapUsers = feiShuXdapUserDao.getXdapUserInfo(webhookProcessDto.getApaasProcNotificationLog().getReceiver(), webhookProcessDto.getTenantId(), "xdap_users");
        approvalBotSend.setUserId(xdapUsers.getRefId());
        //唯一值
        approvalBotSend.setUuid(UUID.randomUUID().toString());
        //bot标题
        approvalBotSend.setCustomTitle("@i18n@1");
        //bot内容
        approvalBotSend.setCustomContent("@i18n@2");
        //行动区
        List<ApprovalBotActions> approvalBotActionsList = new ArrayList<>();
        ApprovalBotActions approvalBotActions = new ApprovalBotActions();
        approvalBotActions.setActionName("@i18n@4");

        XdapProcInstanceDto xdapProcInstanceDto = new XdapProcInstanceDto();
        xdapProcInstanceDto.setFormId(webhookProcessDto.getApaasProcNotificationLog().getFormId());
        String menuid = approveDao.selectMenusId(webhookProcessDto.getApaasProcNotificationLog().getFormId(),webhookProcessDto.getTenantId()).getId();
        xdapProcInstanceDto.setMenuId(menuid);
        xdapProcInstanceDto.setDocumentId(webhookProcessDto.getApaasProcNotificationLog().getDocumentId());
        xdapProcInstanceDto.setAppId(webhookProcessDto.getAppId());
        xdapProcInstanceDto.setTenantId(webhookProcessDto.getTenantId());
        webhookProcessDto.setXdapProcInstance(xdapProcInstanceDto);
        LinksDTO linksDTO = buildLikeUrl(webhookProcessDto,true);
        log.info("发送知会消息跳转链接："+JSONObject.toJSONString(linksDTO));
        approvalBotActions.setAndroidUrl(linksDTO.getMobileLink());
        approvalBotActions.setUrl(linksDTO.getPcLink());
        approvalBotActions.setIosUrl(linksDTO.getMobileLink());
        approvalBotActions.setPcUrl(linksDTO.getPcLink());
        approvalBotActionsList.add(approvalBotActions);
        approvalBotSend.setActions(approvalBotActionsList);
        //国际化文案
        List<ApprovalBotI18nResources> i18nResourcesList = new ArrayList<>();
        ApprovalBotI18nResources i18nResources = new ApprovalBotI18nResources();
        i18nResources.setIsDefault(true);
        i18nResources.setLocale("zh-CN");
        ApprovalBotI18nResourcesTexts texts = new ApprovalBotI18nResourcesTexts();
        texts.setActionName1("查看详情");
        String creatName =  feiShuXdapUserDao.getXdapUserInfo(webhookProcessDto.getApaasProcNotificationLog().getSubmitter(), webhookProcessDto.getTenantId(), "xdap_users").getUsername();
        String customContent = "**流程详情:**\n" +creatName+"提交的流程知会了你，请查阅！" ;
        texts.setCustomContent(customContent);
        //bot标题
        texts.setCustomTitle("流程知会");
        i18nResources.setTexts(texts);
        i18nResourcesList.add(i18nResources);
        approvalBotSend.setI18nResources(i18nResourcesList);
        log.info("发送知会消息："+JSONObject.toJSONString(approvalBotSend));
        ResponseEntity mapResponseEntity = sendBot(approvalBotSend);
        log.info("发送知会Bot消息结果：" + mapResponseEntity.getBody());
        return (String) mapResponseEntity.getBody();

    }
    /**
     * 发送bot卡片
     * @param approvalBotSend
     * @return
     */
    public ResponseEntity sendBot (ApprovalBotSend approvalBotSend){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Authorization", "Bearer " + feishuService.getToken());
        httpHeaders.set("Content-Type", ContentType);
        HttpEntity<JSONObject> httpEntity = new HttpEntity(JSONObject.toJSONString(approvalBotSend), httpHeaders);
        log.info(JSONObject.toJSONString(approvalBotSend));
        ResponseEntity<String> mapResponseEntity = restTemplate.postForEntity(sendApprovalBotUrl, httpEntity, String.class);
        log.info("发送审批Bot消息结果：" + mapResponseEntity.getBody());
        return mapResponseEntity;
    }


}

